package com.lei.study.mvel.high;

import com.sun.tools.javac.util.ArrayUtils;
import org.mvel2.MVEL;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.IndexVariableResolver;
import org.mvel2.integration.impl.MapVariableResolverFactory;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.Math;

/**
 * @author 伍磊
 */
public class HighTest {

    /**
     * 定义add
     */
    private static final String add = "def add(a, b) { return a + b; }";

    private static final String sub = "def add(a, b) { return a - b; }";

    private static final String avg = "def AVG(avgs) {\n" +
            "    count = avgs.length;\n" +
            "    sum = 0;\n" +
            "    for (int i = 0; i < count; i++) {\n" +
            "        sum += avgs[i];\n" +
            "    }\n" +
            "    return sum / count\n" +
            "}\n" +
            "\n";

    private static final String SUB = "import java.math.BigDecimal;\n" +
            "def sub(a, b) {\n" +
            "     return new BigDecimal(Double.toString(a)).subtract(new BigDecimal(Double.toString(b)));\n" +
            "}";

    private static final Map<String, Object> map = new HashMap<>();


    public static void main(String[] args) {

        //test1();

        test2();


    }

    private static void test1() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(add);
        stringBuilder.append(avg);

        map.put("REV", 2);
        map.put("REVF", 3);
        map.put("REVZ", "4");
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6);
        map.put("avgs", integers.toArray());
        Object o = MVEL.eval(stringBuilder.append("AVG(avgs)").toString(), map);
        System.out.println(o);
    }

    private static void test2() {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(SUB);

        map.put("REV", 0.0180000012312312);
        map.put("REVF", 0.0160000012312311);

        VariableResolverFactory variableResolverFactory = new MapVariableResolverFactory(map);
        Object o = MVEL.eval(stringBuilder.append("sub(REV, REVF)").toString(), variableResolverFactory);
        System.out.println(o);
    }
}
